﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Dapper;
using PMS.IRepository;
using PMS.Utils;

namespace PMS.Repository
{
    //public class BaseRepository<T> : IBaseRepository<T> where T : class, new()
    public class BaseRepository<T> where T : class, new()
    {
        #region Init IDbConnection

        private readonly string _connString = ConfigurationManager.ConnectionStrings["Default"].ConnectionString;

        private IDbConnection _dbConn;

        public IDbConnection DbConn
        {
            get
            {
                _dbConn = new SqlConnection(_connString);
                _dbConn.Open();
                return _dbConn;
            }
        }

        #endregion

        /// <summary>
        /// 获取分页字段
        /// </summary>
        /// <param name="orderFile">排序字段</param>
        /// <param name="sort">排序方式 asc or desc</param>
        /// <returns></returns>
        public string GetPageWhere(string orderFile, string sort)
        {
            return " RowNumber Over( order by " + orderFile + " " + sort.ToOrderSort() + ") 'rowNum' ";
        }


        public List<T> GetList(string strSql, Dictionary<string, object> param)
        {
            using (DbConn)
            {
                return DbConn.Query<T>(strSql, param).ToList();
            }
        }

        public List<T> GetList(string strSql, Dictionary<string, object> param, IDbTransaction tran)
        {
            using (DbConn)
            {
                return DbConn.Query<T>(strSql, param, tran).ToList();
            }
        }

        public List<T> GetList(string strSql, Dictionary<string, object> param, IDbTransaction tran, int commandTime)
        {
            using (DbConn)
            {
                return DbConn.Query<T>(strSql, param, tran, true, commandTime).ToList();
            }
        }

        public List<T> GetList(string strSql, Dictionary<string, object> param, IDbTransaction tran, int commandTime, CommandType commandType)
        {
            using (DbConn)
            {
                return DbConn.Query<T>(strSql, param, tran, true, commandTime, commandType).ToList();
            }
        }


        public virtual  int GetMaxId()
        {
            throw new System.NotImplementedException();
        }
    }
}
